package com.tiantianfresh.model.web;

import com.tiantianfresh.admin.service.PermissionService;
import com.tiantianfresh.model.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author FANGAO
 * @date 2021/11/16 - 下午 21:18
 */
public class Authlnterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //获取当前访问路径
        String uri = request.getRequestURI();
        String path = request.getSession().getServletContext().getContextPath();
        //判断当前路径是否需要验证
        //查询所有需要验证的路径集合
        List<Permission> permissionList = permissionService.queryAll();
        //将所有许可路径放入set集合中（set集合可以防止重复）
        Set<String> uriSet = new HashSet<String>();
        for (Permission permission : permissionList) {
            if (permission.getUrl()!=null && !"".equals(permission.getUrl())) {
                uriSet.add(path+permission.getUrl());
            }
        }
        //判断当前路径是否是许可路径是的话需要处理
        if (uriSet.contains(uri)){
            //拿到当前登录用户的所有许可路径
            Set<String> authUriSet = (HashSet<String>) request.getSession().getAttribute("authUriSet");
            //如果用户许可路径中有此路径说明用户有此权限
            if (authUriSet.contains(uri)){
                //有权限的话允许访问
                return true;
            }else{
                //没权限的话进入错误页面
                response.sendRedirect(path+"/goError");
                return false;
            }
        }else{
            //不是许可路径的话直接放行
            return true;
        }
        //return true;
    }
}
